package com.lancoo.ccas53.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.lancoo.ccas53.arrangecourse.ArrangeCourseDataSource;
import com.lancoo.ccas53.entity.Room;
import com.lancoo.ccas53.entity.TeachingClassWeek;
import com.lancoo.ccas53.entity.Type;
import com.lancoo.ccas53.mapper.TeachingClassMapper;
import com.lancoo.ccas53.pojo.dto.ArrangePeriod;
import com.lancoo.ccas53.pojo.dto.ArrangeRoomDto;
import com.lancoo.ccas53.pojo.dto.ArrangeRoomRuleDto;
import com.lancoo.ccas53.pojo.dto.ArrangeTeachingClassDto;
import com.lancoo.ccas53.pojo.vo.RoomCheckVo;
import com.lancoo.ccas53.pojo.vo.WeekDateVo;
import com.lancoo.ccas53.service.RoomService;
import com.lancoo.ccas53.service.TeachingClassService;
import com.lancoo.ccas53.service.TeachingClassWeekService;
import com.lancoo.ccas53.service.TypeService;
import com.lancoo.ccas53.util.ResponseObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liufeng
 * @CreateTime: 2025-01-24  11:02
 * @Description:
 */
@Service
public class TimeSlotCheckService {

    @Resource
    private TeachingClassMapper teachingClassMapper;
    @Resource
    private ArrangeCourseDataSource arrangeCourseDataSource;
    @Resource
    private RoomService roomService;
    @Resource
    private TeachingClassWeekService teachingClassWeekService;

    public ResponseObject<Object> roomCheck1(Integer taskId, String schoolId, String term, Integer collegeId) {
        List<ArrangeTeachingClassDto> allTeachingClass = teachingClassMapper.getAllTeachingClass1(taskId);
        Map<Integer, List<Room>> roomMap = roomService.lambdaQuery().eq(Room::getTaskId, taskId)
                .isNotNull(Room::getRoomType).list()
                .stream().collect(Collectors.groupingBy(Room::getRoomType));
        for (ArrangeTeachingClassDto teachingClass : allTeachingClass) {
            List<Room> roomList = roomMap.get(teachingClass.getRoomType());
            if (roomList != null && roomList.size() == 1){
                Room room = roomList.get(0);
                teachingClassWeekService.lambdaUpdate()
                        .eq(TeachingClassWeek::getId,teachingClass.getId())
                        .set(TeachingClassWeek::getRoomId,room.getRoomId())
                        .set(TeachingClassWeek::getRoomName,room.getRoomName())
                        .update();
            }
        }


        return null;
    }

    public ResponseObject<Object> roomCheck(Integer taskId, String schoolId, String term, Integer collegeId) {
        List<ArrangeTeachingClassDto> allTeachingClass = teachingClassMapper.getAllTeachingClass(taskId);
        if (CollUtil.isEmpty(allTeachingClass)) {
            return ResponseObject.ofSuccess();
        }
        WeekDateVo weekInfo = arrangeCourseDataSource.getTermWeeks(taskId);
        //获取学期总周数，默认16周
        Long weekNum = 16L;
        if (weekInfo != null) {
            //获取学期总周数
            weekNum = weekInfo.getWeekCount();
        }
        List<ArrangeRoomDto> roomList = arrangeCourseDataSource.getRoomList(taskId, schoolId, term, null);
        List<Long> roomIds = allTeachingClass.stream().map(ArrangeTeachingClassDto::getRoomId).distinct().collect(Collectors.toList());
        roomList = roomList.stream().filter(o -> roomIds.contains(o.getRoomId())).collect(Collectors.toList());

        List<ArrangeRoomRuleDto> roomProhibitList = arrangeCourseDataSource.getRoomRuleList(taskId, schoolId, term, null, null);
        Map<Long, List<ArrangeRoomRuleDto>> roomProhibitMap = roomProhibitList.stream().collect(Collectors.groupingBy(ArrangeRoomRuleDto::getRoomId));

        List<ArrangePeriod> timeslotList = arrangeCourseDataSource.getTimeslotList(taskId, schoolId, term, null);
        long timeCodes = timeslotList.stream().filter(o -> o.getIsProhibit().equals(0)).count();

        Map<Long, List<ArrangeTeachingClassDto>> teachingClassRoomMap = allTeachingClass.stream().collect(Collectors.groupingBy(ArrangeTeachingClassDto::getRoomId));
//
        List<RoomCheckVo> res = new ArrayList<>();
//        StringBuilder res = new StringBuilder();
        String format = "教室：{} 第{}周 课时方案总课时：{}，教室禁排课时：{}，教学占用最大周总课时：{} \n 教学班：{}";

        for (ArrangeRoomDto room : roomList) {
            List<ArrangeTeachingClassDto> teachingClassList = teachingClassRoomMap.get(room.getRoomId());
            int prohibitSize = roomProhibitMap.containsKey(room.getRoomId()) ? roomProhibitMap.get(room.getRoomId()).size() : 0;
            long max = 0;
            List<String> weeks = new ArrayList<>();
            Set<String> classNames = new HashSet<>();
            for (int i = 0; i < weekNum; i++) {
                int index = i;
                List<ArrangeTeachingClassDto> weekClass = teachingClassList.stream().filter(o -> o.getWeek().charAt(index) == '1').collect(Collectors.toList());
                long classWeekSum = weekClass.stream().mapToLong(ArrangeTeachingClassDto::getWeekNum).sum();

                long leave = timeCodes - prohibitSize - classWeekSum;

                if (leave < 0){
                    max = Math.max(max,classWeekSum);
                    weeks.add(String.valueOf(i + 1));
                    classNames.addAll(weekClass.stream().map(ArrangeTeachingClassDto::getTeachingClassName).distinct().collect(Collectors.toList()));
                }
            }
            if (CollUtil.isNotEmpty(weeks)){
                res.add(new RoomCheckVo().setRoomName(room.getRoomName())
                        .setWeek( String.join(",", weeks))
                        .setPeriodScheme(timeCodes)
                        .setProhibit(prohibitSize)
                        .setScheduleMax(max)
                        .setTeachingClass(String.join("，",classNames)));

//                res.append(StrUtil.format(format, room.getRoomName(), String.join(",", weeks), timeCodes, prohibitSize, max));
            }
        }

//        if (StrUtil.isNotEmpty(res.toString())){
//            throw new BizException(res.toString());
//        }

        return ResponseObject.ofSuccess(res);
    }
}
